# Server

::: tip 
In most cases, you might not need the Agent TARS Server. However, when we later allow custom Web UI functionality, this document will be very helpful to you.
:::

The Agent TARS Server is a server-side component in the Agent TARS ecosystem built on top of Agent TARS Core. It includes capabilities such as session storage management and a Web UI:

```bash
agent-tars serve
```

import { Figure } from '@components/Figure';

<Figure src="/agent-tars-serve.png" maxWidth="75%" title="Agent TARS Headless Server" />

## Basic Concepts

Agent TARS Server handles two main concepts:

1. **Session**: Represents a complete Agent TARS interaction context, containing message history, tool calls, and state information
2. **Query**: A single request executed within a session, which can be text or multimodal content

By default, Agent TARS Server's base path is `/api/v1`, through which you can access various server endpoints.

## Server Configuration

Agent TARS Server offers multiple configuration options, including port settings, storage configuration, working directory, and sharing options. These configurations can be set through the Agent TARS configuration file.

```bash
agent-tars serve --port 8888
```

```ts
// agent-tars.config.ts
export default {
  server: {
    port: 8888,
    // Other server configurations...
  },
  // Other configurations implemented by server.
};
```

## Session Management API

Agent TARS Server provides a complete session lifecycle management API:

### Create Session

Create a new Agent session:

```bash
POST /api/v1/sessions/create
```

Response:

```json
{
  "sessionId": "unique-session-id"
}
```

### Get Session List

Retrieve all sessions:

```bash
GET /api/v1/sessions
```

Response:

```json
{
  "sessions": [
    {
      "id": "session-id-1",
      "createdAt": 1622548800000,
      "updatedAt": 1622548800000,
      "name": "Session Name",
      "workingDirectory": "/path/to/workspace",
      "tags": ["tag1", "tag2"]
    }
    // ...more sessions
  ]
}
```

### Get Session Details

Get detailed information for a specific session:

```bash
GET /api/v1/sessions/details?sessionId=session-id
```

### Get Session Status

Get the current running status of a session:

```bash
GET /api/v1/sessions/status?sessionId=session-id
```

Response:

```json
{
  "sessionId": "session-id",
  "status": {
    "isProcessing": false,
    "state": "idle"
  }
}
```

### Get Session Events

Retrieve historical events for a specific session:

```bash
GET /api/v1/sessions/events?sessionId=session-id
```

### Get Latest Session Events

Retrieve events from the most recently updated session:

```bash
GET /api/v1/sessions/events/latest
```

### Update Session

Update session metadata:

```bash
POST /api/v1/sessions/update
```

Request body:

```json
{
  "sessionId": "session-id",
  "name": "New Session Name",
  "tags": ["tag1", "tag2"]
}
```

### Delete Session

Delete a specific session and all its events:

```bash
POST /api/v1/sessions/delete
```

Request body:

```json
{
  "sessionId": "session-id"
}
```

### Generate Summary

Generate a summary for a session's conversation:

```bash
POST /api/v1/sessions/generate-summary
```

Request body:

```json
{
  "sessionId": "session-id",
  "messages": [...],
  "model": "optional-model-name",
  "provider": "optional-provider-name"
}
```

## Query Execution API

Agent TARS Server supports two query execution modes: standard mode and streaming mode.

### Execute Standard Query

```bash
POST /api/v1/sessions/query
```

Request body:

```json
{
  "sessionId": "session-id",
  "query": "Hello, Agent TARS!"
}
```

For multimodal queries, query can be an array of content parts with text and images:

```json
{
  "sessionId": "session-id",
  "query": [
    { "type": "text", "text": "What's in this image?" },
    { 
      "type": "image_url", 
      "image_url": {
        "url": "data:image/jpeg;base64,..."
      }
    }
  ]
}
```

### Execute Streaming Query

Streaming queries allow you to get real-time responses:

```bash
POST /api/v1/sessions/query/stream
```

The request body is the same as for standard queries, but responses will be streamed in Server-Sent Events (SSE) format.

### Abort Query

Interrupt a currently executing query:

```bash
POST /api/v1/sessions/abort
```

Request body:

```json
{
  "sessionId": "session-id"
}
```

## One-shot API

For convenience, Agent TARS Server provides one-shot APIs that create a session and execute a query in one step:

### One-shot Query (Non-streaming)

```bash
POST /api/v1/oneshot/query
```

Request body:

```json
{
  "query": "Hello, Agent TARS!",
  "sessionName": "Optional session name",
  "sessionTags": ["optional", "tags"]
}
```

### One-shot Query (Streaming)

```bash
POST /api/v1/oneshot/query/stream
```

The request body is the same as for non-streaming one-shot queries, but responses will be streamed in SSE format.

## System API

### Health Check

Check server status:

```bash
GET /api/v1/health
```

Response:

```json
{
  "status": "ok"
}
```

## Sharing Functionality

Agent TARS Server provides powerful session sharing capabilities, allowing export and sharing of session history.

### Get Sharing Configuration

```bash
GET /api/v1/share/config
```

### Share Session

```bash
POST /api/v1/sessions/share
```

Request body:

```json
{
  "sessionId": "session-id",
  "upload": true
}
```

Response:

```json
{
  "success": true,
  "url": "https://share-provider.com/shared-session-id"
}
```

## WebSocket Communication

In addition to RESTful API, Agent TARS Server also provides WebSocket interfaces for real-time bidirectional communication.

### Connect to a Session

```javascript
// Client code
const socket = io('http://localhost:8888');

// Join a specific session
socket.emit('join-session', 'session-id');

// Listen for events
socket.on('agent-event', (event) => {
  console.log('Received event:', event);
});

// Send a query
socket.emit('send-query', {
  sessionId: 'session-id',
  query: 'Hello, Agent TARS!'
});

// Abort a query
socket.emit('abort-query', { sessionId: 'session-id' });
```

## Browser Control Information

Get browser control mode information:

```bash
GET /api/v1/sessions/browser-control?sessionId=session-id
```

## Storage Providers

Agent TARS Server supports multiple storage providers for persistence:

1. **Memory Storage** - In-memory storage (default, data lost on restart)
2. **File Storage** - JSON file-based persistence
3. **SQLite Storage** - SQLite database for better performance with large datasets

Storage can be configured in the config file:

```ts
// agent-tars.config.ts
export default {
  server: {
    storage: {
      type: 'sqlite', // 'memory', 'file', or 'sqlite'
      path: '~/.agent-tars' // Optional path for file/sqlite storage
    }
  }
};
```

## Usage

::: warning Important

Agent TARS Server is currently in early iteration, and APIs may change. It is currently recommended to use it through the built-in integration in Agent TARS CLI only, and not to directly depend on its APIs for development. We will provide self-deployment guides and stable SDK documentation in the future.

:::

### Using from Agent TARS CLI

Start the server using CLI:

```bash
agent-tars serve --port 8888
```

You can specify server options in the configuration file:

```ts
// agent-tars.config.ts
export default {
  server: {
    port: 8888,
    open: true,  // Automatically open browser
  }
};
```

### Middleware Extensions

Agent TARS Server is based on Express and Connect middleware architecture and can extend server functionality through APIs:

```ts
// In a custom script
import { AgentTARSServer } from '@agent-tars/server';

const server = new AgentTARSServer(config);
const app = server.getApp();

// Add custom middleware
app.use('/custom-endpoint', (req, res) => {
  res.json({ message: 'Hello from custom endpoint!' });
});

await server.start();
```

### Event Stream Processing

Agent TARS Server uses structured event streams for communication. Each event has a specific type and format, such as: user messages, assistant replies, tool calls, and system events.

Here's a typical event stream:

```javascript
[
  { type: 'user_message', content: 'User query', timestamp: 1622548800000, id: '...' },
  { type: 'assistant_streaming_message', content: 'Assistant', timestamp: 1622548800100, id: '...' },
  { type: 'tool_call', name: 'web_search', arguments: {...}, timestamp: 1622548800200, id: '...' },
  { type: 'tool_result', name: 'web_search', content: {...}, timestamp: 1622548800300, id: '...' },
  { type: 'assistant_message', content: 'Final response', timestamp: 1622548800400, id: '...' }
]
```
